
import pandas as pd
from datetime import datetime


def process_date(time_str):
    """
    处理时间的函数
    :param time_str: 2020年01月01日 01:03
    :return: 2020-01-01 05:21
    """
    datetime_obj = datetime.strptime(time_str, '%Y年%m月%d日 %H:%M')               # 将时间字符串解析为datetime对象
    formatted_time = datetime_obj.strftime('%Y-%m-%d')                            # 格式化为可比较的字符串

    return formatted_time


def main():
    """
    主函数
    :return: 无返回值
    """
    data = pd.read_csv(r"D:\file\Mechine_learning\before\2020_0.csv", encoding="utf-8")
    data_list = []                                                                # 创建一个空列表,用于存储数据字典

    i = 0                                                                         # 用于记数第几条数据，并且用于查找下一条数据
    while data.iloc(0)[i][1] != None:                                                        # 当为空的时候停止循环
        try:
            data_dict = {"date": process_date(data.iloc(0)[i][1])}
            data_list.append(data_dict)
        except ValueError as e:
            print(e)

        i += 1
        print("第", i, "个")
        if i >= 10475:
            break
    print(data_list)

    date_counts = {}
    for my_dict in data_list:
        date_str = my_dict['date']                                                 # '2020-01-01 01:03'
        if date_str in date_counts:
            date_counts[date_str] += 1
        else:
            date_counts[date_str] = 1

    df = pd.DataFrame(list(date_counts.items()), columns=['Date', 'Value'])
    df.to_excel(r"D:\file\Mechine_learning\after\2020_0.xlsx", index=False)


if __name__ == '__main__':
    main()
